package com.atguigu.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("file")
public class FileController {
    @Autowired
    private ServletContext servletContext;
    @PostMapping("upload")
    public Object upload(@RequestParam String account,
                         @RequestParam String password,
                         @RequestParam("file") MultipartFile header) throws IOException {
        String originalFilename = header.getOriginalFilename();
        System.out.println(account+"--------"+password+"--------"+originalFilename);
        String name = header.getName();
        System.out.println(name);
        byte[] bytes = header.getBytes();
        System.out.println(bytes.length);
        return "success";
    }
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
     //获取土坯懒得全称限定名
        String realPath = servletContext.getRealPath("/imags/hl.jpg");
        //读取图片
        FileInputStream fis = new FileInputStream(realPath);
        //设置响应头作用是设置下载图片而不是打开
        response.setHeader("content-disposition","attachment;filename=hl.jpg");
        //准备输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //准备shu组
        byte[] bytes = new byte[8 * 1024];
        //将图片从输入流装到输出流中
        int len =-1;
        while((len=fis.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
    }
}
